package com.ldk.framework.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ldk.base.framework.util.SystemUtil;
import com.ldk.framework.entity.PushMessage;
import com.ldk.framework.entity.ServiceTrip;
import com.ldk.framework.push.CustomMsgModule;
import com.ldk.framework.push.CustomMsgType;
import com.ldk.framework.push.PushCustomMsg;
import com.ldk.framework.push.PushTargetApp;
import com.ldk.framework.service.IPushMessageService;

/**
 * 包车用户行程推送给司机
 * @author xiangwl
 * 2017年3月24日
 * com.ldk.framework.service.impl
 * BCUserTripPushToDriverThread
 */
@Component
public class BCUserTripPushToDriverThread implements Runnable {
	private final Logger LOGGER = LoggerFactory.getLogger(ZXPCUserTripPushToDriverThread.class);
	/**
	 * 包车业务搜索司机是，客户端已经选好司机的，所以不需要做搜索过程直接就把用户行程信息推送给司机
	 * 是否自定派单机制 放在外面判断
	 */

	/**
	 * 用户行程
	 */
	private ServiceTrip userTrip;
	
	@Autowired
	private IPushMessageService pushMessageService;
	
	public BCUserTripPushToDriverThread(ServiceTrip userTrip){
		this.userTrip = userTrip;
	}
	public BCUserTripPushToDriverThread() {
	}
	public void setUserTrip(ServiceTrip userTrip) {
		this.userTrip = userTrip;
	}

	@Override
	public void run() {
		try{
			if(userTrip == null) return;
			final String tripNo = userTrip.getTripNo();
			String driverOpenId = userTrip.getDriverOpenId();
			//判断是否推送过个这个司机
			PushMessage query = new PushMessage();
			query.setToUser(driverOpenId);
			query.setTripNo(tripNo);
			
			long count = pushMessageService.selectCount("", query);
			if(count > 0) return;
			
			String serviceCode = userTrip.getServiceCode();
			List<String> aliasList = new ArrayList<String>();
			aliasList.add(userTrip.getDriverOpenId());
			String toUser = driverOpenId;
			String moduleName = CustomMsgModule.getModuleName(serviceCode);
			String message = String.format("%s新行程",moduleName);
			String content = String.format("[%s]%s-%s新行程",moduleName, userTrip.getStartLocation(), userTrip.getEndLocation());
			PushCustomMsg customMsg = new PushCustomMsg();
			customMsg.setModule(serviceCode);
			customMsg.setType(CustomMsgType.UserNewTrip.getValue());
			customMsg.setKey(tripNo);

			PushMessage pushMessage = new PushMessage();
			pushMessage.setContent(content);
			pushMessage.setModule(serviceCode);
			pushMessage.setTitle(message);
			pushMessage.setTripNo(tripNo);
			pushMessage.setToUser(toUser);
			pushMessage.setMessage(message);
			pushMessage.setContent(content);
			pushMessage.setExtras(customMsg.toJson());
			pushMessage.setPushTime(SystemUtil.getAllSeconds());
			pushMessage.setJumpUrl("");

			pushMessageService.pushToUser("", pushMessage, PushTargetApp.Driver, customMsg, aliasList, true);
		}
		catch(Exception e){
			LOGGER.error(e.getMessage());
		}
		
	}
}
